package com.hnucm.viewpager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.media.Image;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;

import com.hnucm.viewpager.adapter.MyViewPagerAdapter;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

/*
 * 1.写布局文件，添加一个viewpager控件
 * 2.在Activity中获取实例
 * 3.创建一个数据-视图适配器adapter
 * 4.创建一个myViewPagerAdapter实例
 * 5.初始化数据
 * 6.将数据添加到适配器中
 * 7.布局与适配器绑定
 * 8.addOnPageChangeListener()添加事件响应
 *
 */
    private ViewPager viewPager;
    private MyViewPagerAdapter myViewPagerAdapter;
    private List<ImageView> imageViewList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        获取实例
        viewPager=findViewById(R.id.viewpager1);
//        初始化数据
        initData();
//        将数据添加到适配器中
        myViewPagerAdapter=new MyViewPagerAdapter(imageViewList);
//        布局与适配器绑定
        viewPager.setAdapter(myViewPagerAdapter);
//        添加事件响应
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Toast.makeText(MainActivity.this,"你先中了第"+position+"页",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }

    private void initData() {
        ImageView imageView1=new ImageView(this);
        imageView1.setImageResource(R.drawable.img1);
        imageView1.setScaleType(ImageView.ScaleType.FIT_XY);

        ImageView imageView2=new ImageView(this);
        imageView2.setImageResource(R.drawable.img2);
        imageView2.setScaleType(ImageView.ScaleType.FIT_XY);

        ImageView imageView3=new ImageView(this);
        imageView3.setImageResource(R.drawable.img3);
        imageView3.setScaleType(ImageView.ScaleType.FIT_XY);


        imageViewList=new ArrayList<>();
        imageViewList.add(imageView1);
        imageViewList.add(imageView2);
        imageViewList.add(imageView3);
    }
}